package ui.finance;

import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

import javax.swing.JPanel;

import o.财务单据类型;
import tool.LongStringTransformer;
import tool.MyButton;
import tool.MyLabel;
import vo.AccountorVo;
import vo.ClientVo;
import vo.Vo;
import vo.AccountInAndOutDocumentVo;
import vo.AccountItemVo;
import vo.UserVo;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import client.boot.BLServiceManager;
import blservice.client.ClientBLService;
import blservice.document.DocumentBLService;
import blservice.finance.AccountorBLService;

import java.awt.Font;
import java.awt.Color;

public class 收付款单Panel extends JPanel {
	private static final long serialVersionUID = 2586353259038592152L;

	DocumentBLService documentsBL;

	AccountInAndOutDocumentVo vo;
	UserVo user;
	private JComboBox<String> client;
	private JTable table;
	private JScrollPane jsp;
	private JTextField number;
	private JTextField operator;
	private JTextField sum;
	private boolean isNew;
	private boolean editable;
	private Vector<String> accountNames = new Vector<String>();;
	private 财务单据类型 type;
	private boolean 审批;
	private boolean 红冲;

	/**
	 * 
	 * @param user
	 * @param vo
	 *            如果是单据查询，则传入vo，如果是单据制定则传入null;
	 * @param editable
	 *            如果是新建或者红冲并复制就设置成editable
	 * @param 红冲
	 */
	public 收付款单Panel(UserVo user, AccountInAndOutDocumentVo vo, boolean editable, 财务单据类型 type,
			boolean 审批, boolean 红冲) {
		this.红冲 = 红冲;
		this.审批 = 审批;
		this.user = user;
		this.setLayout(null);
		this.setOpaque(false);
		this.editable = editable;
		this.type = type;
		if (vo == null) {
			isNew = true;
			this.vo = new AccountInAndOutDocumentVo();
		} else {
			isNew = false;
			this.vo = vo;
		}
		JLabel label = new JLabel(type.name() + "\u5236\u5B9A");
		label.setForeground(Color.WHITE);
		label.setFont(new Font("微软雅黑", Font.PLAIN, 18));
		label.setBounds(273, 10, 93, 21);
		add(label);

		JLabel label_1 = new MyLabel("\u5355\u636E\u7F16\u53F7\uFF1A");
		label_1.setBounds(47, 53, 75, 15);
		add(label_1);

		JLabel label_2 = new MyLabel("\u5BA2\u6237\uFF1A");
		label_2.setBounds(47, 78, 54, 15);
		add(label_2);

		client = new JComboBox<String>();
		client.setBounds(122, 75, 105, 21);
		add(client);

		JLabel label_3 = new MyLabel("\u8F6C\u8D26\u5217\u8868");
		label_3.setBounds(47, 100, 54, 15);
		add(label_3);

		JButton add = new MyButton("Graphics/Button45-23.png");
		add.setText("+");
		add.setBounds(465, 96, 45, 23);
		if (!editable) {
			add.setVisible(false);
		}
		add.addActionListener(e -> addLine());
		add(add);

		JLabel label_4 = new MyLabel("业务员：");
		label_4.setBounds(370, 53, 54, 15);
		add(label_4);

		JLabel label_5 = new MyLabel("\u603B\u989D\uFF1A");
		label_5.setBounds(47, 387, 54, 15);
		add(label_5);

		JButton submit = new MyButton("Graphics/Button93-23.png");
		submit.setText("\u63D0\u4EA4");
		submit.setBounds(489, 383, 93, 23);
		submit.addActionListener(e -> submit());
		if (!editable && !审批 && !红冲) {
			submit.setVisible(false);
		}
		if (审批) {
			submit.setText("通过审批");
		}
		if (红冲) {
			submit.setText("红冲");
		}
		add(submit);

		JButton sub = new MyButton("Graphics/Button45-23.png");
		sub.setText("-");
		sub.setBounds(537, 96, 45, 23);
		sub.addActionListener(e -> subLine());
		if (!editable) {
			sub.setVisible(false);
		}
		add(sub);

		table = new JTable() {
			private static final long serialVersionUID = 3028897666676861555L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return editable;
			}
		};
		table.setBounds(47, 128, 535, 248);
		jsp = new JScrollPane(table);
		jsp.setBounds(47, 128, 535, 248);
		jsp.setVisible(true);
		this.add(jsp);

		number = new JTextField();
		number.setEditable(false);
		number.setColumns(10);
		number.setBounds(122, 50, 105, 21);
		add(number);

		operator = new JTextField();
		operator.setEditable(false);
		operator.setColumns(10);
		operator.setBounds(429, 50, 105, 21);
		if (isNew) {
			operator.setText(user.getName());
		} else {
			operator.setText(vo.get业务员());
		}
		add(operator);

		sum = new JTextField();
		sum.setEditable(false);
		sum.setBounds(122, 384, 105, 21);
		add(sum);
		sum.setColumns(10);

		iniClient();
		iniAccount();

		if (isNew) {
			this.vo.set单据编号("");
			this.vo.set业务员(user.getName());
		}
		display();
	}

	void display() {
		number.setText(vo.get单据编号());
		operator.setText(vo.get业务员());
		client.setSelectedItem(vo.get客户());
		DefaultTableModel model = new DefaultTableModel();
		model.setColumnIdentifiers(new String[] { "银行账户", "转账金额", "备注" });

		for (AccountItemVo o : vo.get转账列表()) {
			model.addRow(new String[] { o.get银行账户(),
					tool.LongStringTransformer.LongToString(o.get转账金额()),
					o.get备注() });

		}
		this.sum.setText(LongStringTransformer.LongToString(vo.get总额汇总()));
		if (editable) {
			model.addRow(new String[] { "", "", "" });
		}
		table.setModel(model);
		if (editable) {
			JComboBox<String> temp = new JComboBox<String>();
			for (String s : accountNames) {
				temp.addItem(s);
			}
			table.getColumnModel().getColumn(0)
					.setCellEditor(new DefaultCellEditor(temp));
		}
	}

	void save() {
		vo.set业务员(user.getName());
		vo.set客户((String) client.getSelectedItem());
		List<AccountItemVo> items = vo.get转账列表();
		items.clear();
		long total = 0;
		for (int i = 0; i < table.getRowCount(); i++) {
			AccountItemVo temp = new AccountItemVo();
			temp.set备注((String) table.getValueAt(i, 2));
			String tempAccountName = (String) table.getValueAt(i, 0);
			boolean successed1 = false;
			for (String s : accountNames) {
				if (s.equals(tempAccountName)) {
					temp.set银行账户(tempAccountName);
					successed1 = true;
					break;
				}
			}
			boolean successed2 = false;

			try {
				long tempMoney = LongStringTransformer
						.StringToLong((String) table.getValueAt(i, 1));
				temp.set转账金额(tempMoney);
				successed2 = true;

			} catch (NumberFormatException e) {
			}
			if (successed1 && successed2) {
				total = total + temp.get转账金额();
				items.add(temp);
			}
		}
		vo.set总额汇总(total);
	}

	void subLine() {
		int line = table.getSelectedRow();
		if (line == -1 || line >= vo.get转账列表().size()) {
			return;
		} else {
			vo.get转账列表().remove(line);
			display();
		}
	}

	void addLine() {
		save();
		display();
	}

	void submit() {
		save();
		display();
		if (vo.get转账列表().size() == 0) {
			JOptionPane.showMessageDialog(this, "请填写转账列表\n");
			return;
		}
		DocumentBLService bl;
		try {
			bl = BLServiceManager.load收付款单BLService(null);
			vo.setOperation("添加" + type.name());
			vo.setOperator(user.getName());
			vo.set单据类型(type);
			Vo result;
			if (审批) {
				result = bl.approve(vo);
			} else if (红冲 && !editable) {
				result = bl.redRush(vo);
			} else if (红冲 && editable) {
				result = bl.redRushAndCopy(vo);
			} else {
				result = bl.add(vo);
			}
			if (result.isSuccessed()) {
				JOptionPane.showMessageDialog(this, "单据提交成功\n");
				vo = new AccountInAndOutDocumentVo();
				display();
			} else {
				JOptionPane.showMessageDialog(this,
						"单据提交失败\n" + result.getFailMessage());
			}
		} catch (RemoteException | MalformedURLException | SQLException
				| NotBoundException e) {
			JOptionPane.showMessageDialog(this, "无法连接到服务器\n" + e.getMessage());
			e.printStackTrace();
		}

	}

	void iniClient() {
		if (editable) {
			try {
				ClientBLService clientBL = BLServiceManager
						.getClientBLService(null);
				List<ClientVo> clientList = clientBL.getAll();
				DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
				for (ClientVo o : clientList) {
					model.addElement(o.get姓名());
				}
				client.setModel(model);

			} catch (RemoteException | MalformedURLException
					| NotBoundException | SQLException e) {
				JOptionPane.showMessageDialog(this,
						"无法连接到服务器\n" + e.getMessage());
				e.printStackTrace();
			}
		} else {
			DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
			model.addElement(vo.get客户());
			client.setModel(model);
			client.setEnabled(false);
		}
	}

	void iniAccount() {
		// 初始化账户列表
		try {
			AccountorBLService clientBL = BLServiceManager
					.getAccountorBLService(null);
			List<AccountorVo> accounts = clientBL.getAll();
			accountNames.clear();
			for (AccountorVo o : accounts) {
				accountNames.add(o.get名称());
			}
		} catch (RemoteException | MalformedURLException | NotBoundException
				| SQLException e) {
			JOptionPane.showMessageDialog(this, "无法连接到服务器\n" + e.getMessage());
			e.printStackTrace();
		}

	}
}
